Nested list weight sum¶
Time: O(N); Space: O(H); easy
Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer, or a list – whose elements may also be integers or other lists.
Example 1:
Input: nestedList = [[1,1],2,[1,1]]
Output: 10
Explanation:
Four 1’s at depth 2, one 2 at depth 1, 4 * 1 * 2 + 1 * 2 * 1 = 10
Example 2:
Input: nestedList = [1,[4,[6]]]
Output: 27
Explanation:
One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4 * 2 + 6 * 3 = 27
1. Recursion¶
[1]:
class Solution1(object):
"""
Time: O(N)
Space: O(H)
"""
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
def depthSumHelper(nestedList, depth):
res = 0
for l in nestedList:
if l.isInteger():
res += l.getInteger() * depth
else:
res += depthSumHelper(l.getList(), depth + 1)
return res
return depthSumHelper(nestedList, 1)
[2]:
s = Solution1()
nestedList = [[1,1],2,[1,1]]
assert s.depthSum(nestedList) == 10
nestedList = [1,[4,[6]]]
assert s.depthSum(nestedList) == 27
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-872528c2eabb> in <module>
2
3 nestedList = [[1,1],2,[1,1]]
----> 4 assert s.depthSum(nestedList) == 10
5
6 nestedList = [1,[4,[6]]]
<ipython-input-1-bdb64c39c809> in depthSum(self, nestedList)
17 res += depthSumHelper(l.getList(), depth + 1)
18 return res
---> 19 return depthSumHelper(nestedList, 1)
20
<ipython-input-1-bdb64c39c809> in depthSumHelper(nestedList, depth)
12 res = 0
13 for l in nestedList:
---> 14 if l.isInteger():
15 res += l.getInteger() * depth
16 else:
AttributeError: 'list' object has no attribute 'isInteger'